extends MeshInstance3D


# StaticBody3D和CollisionShape3D的引用
var static_body: StaticBody3D
var collision_shape: CollisionShape3D

func _ready():
	# 确保cube节点存在

	# 创建StaticBody3D
	static_body = StaticBody3D.new()
	static_body.name = "CubeStaticBody"

	# 创建CollisionShape3D
	collision_shape = CollisionShape3D.new()
	collision_shape.name = "CubeCollisionShape"

	# 创建BoxShape3D（假设Mesh是BoxMesh）
	var box_shape = BoxShape3D.new()
	collision_shape.shape = box_shape

	# 将CollisionShape3D添加到StaticBody3D
	static_body.add_child(collision_shape)

	# 将StaticBody3D添加到场景树（与cube同级）
	get_parent().add_child.call_deferred(static_body)

	# 初始同步
	sync_collision_shape()

func _process(_delta):
	# 每帧同步碰撞形状的变换
	sync_collision_shape()

func sync_collision_shape():
	if not static_body or not collision_shape:
		return

	# 获取MeshInstance3D的全局变换
	var cube_transform = global_transform
	var cube_scale =scale

	# 同步StaticBody3D的位置和旋转
	static_body.global_transform = cube_transform

	# 如果Mesh是BoxMesh，获取其大小并应用到BoxShape3D
	if mesh is BoxMesh:
		var box_mesh = mesh as BoxMesh
		var mesh_size = box_mesh.size * cube_scale
		var box_shape = collision_shape.shape as BoxShape3D
		box_shape.size = mesh_size
